package com.bankcomm.ui.views;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BaseViewCopy;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.utils.Utils;

/**
 * LPWeatherView.java
 * 
 * @author cheng.l 2013-5-18 下午01:27:29
 */
public class LPWeatherView extends LinearLayout implements OnClickListener {

	private BaseViewCopy bv;
	private ImageView ivWeather;
	private ProgressBar refreshBar;
	private TextView tvWeather, tvDate, tvWeek, tvWind, tvTemperature, tvHome_city;

	private String low;//最低气温
	private String high;//最高气温
	private String code;//天气图片
	private String name;//天气状况
	private String wind;//风向
	// 取出存储的城市
	String saveCity = null;
    
	public LPWeatherView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		bv = (BaseViewCopy) context;
		saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
		init();
	}

	public LPWeatherView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		bv = (BaseViewCopy) context;
		saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		LayoutInflater.from(bv).inflate(R.layout.layout_weather_view, this);
		
		tvHome_city = (TextView)this.findViewById(R.id.home_city);
		
		// 天气图片
		ivWeather = (ImageView) this.findViewById(R.id.weatherIcon);
		
		// 天气状况
		tvWeather = (TextView) this.findViewById(R.id.now_weather);
		tvWeather.getPaint().setFakeBoldText(true);
		
		// 日期
		tvDate = (TextView) this.findViewById(R.id.now_date);
		tvDate.setText(getDate());
		// 星期
		tvWeek = (TextView) this.findViewById(R.id.now_week);
		tvWeek.setText(Utils.getDayOfWeek(bv, Calendar.getInstance()));
		// 温度
		tvTemperature = (TextView) this.findViewById(R.id.weatherTemperature);
		// 风力
		tvWind = (TextView) this.findViewById(R.id.weatherWind);
		
		// 刷新进度条
		refreshBar = (ProgressBar) this.findViewById(R.id.refresh_weather);
		refreshBar.setVisibility(View.GONE);

//		this.addView(view, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
		this.setBackgroundResource(R.drawable.w_img_bg);
		
		// 判断是否隐藏提示信息
		if (saveCity != null && !saveCity.equals("")) {
			showView(true);
		} else {
			showView(false);
		}
	}

	/**
	 * 默认刷新天气预报
	 */
	public void refresh(){
//		String saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
		if(null != saveCity && !"".equalsIgnoreCase(saveCity)){
			String[] city =  saveCity.split("\\|");
			startRefresh(city[1]);
		}
	}
	/**
	 * 得到当前的日期 xxxx年xx月xx日
	 * @return
	 */
	public String getDate(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
		return format.format(new Date());
	}

	/**
	 * 更新城市
	 */
	private void updateWeather(){
		tvWeather.setText(name);
		tvDate.setText(getDate());
		tvWeek.setText(Utils.getDayOfWeek(bv, Calendar.getInstance()));
		
		tvWind.setText(" "+wind);
		if(!low.equalsIgnoreCase("N/A")){
			tvTemperature.setText(" "+low+"～"+high+"℃");			
		}else{
			tvTemperature.setText("  N/A");	
		}
		
		int resourceId = Utils.getResourcesId(bv, "weather_"+code, "drawable");
		if(resourceId > -1){
			ivWeather.setImageResource(resourceId);	
		}
	}
	
	/**
	 * 释放资源
	 */
	public void releaseResources() {
		Utils.releaseObject(ivWeather);
		Utils.releaseObject(this);
	}

	public void startRefresh(String name) {
		// 刷新信息时判断是否显示提示信息
		if (null != name && !"".equals(name)) {
			tvHome_city.setText("");
			showView(true);
		} else {
			tvHome_city.setText(bv.getResources().getString(R.string.home_city));
			showView(false);
		}
		new AsyncRefreshTask().execute(name);
	}
	
	private void showView(boolean isBoolean){
		
		if (isBoolean) {
			tvHome_city.setVisibility(View.GONE);
			ivWeather.setVisibility(View.VISIBLE);
			tvWeather.setVisibility(View.VISIBLE);
			tvDate.setVisibility(View.VISIBLE);
			tvWeek.setVisibility(View.VISIBLE);
			tvWind.setVisibility(View.VISIBLE);
			tvTemperature.setVisibility(View.VISIBLE);
		} else {
			tvHome_city.setVisibility(View.VISIBLE);
			ivWeather.setVisibility(View.GONE);
			tvWeather.setVisibility(View.GONE);
			tvDate.setVisibility(View.GONE);
			tvWeek.setVisibility(View.GONE);
			tvWind.setVisibility(View.GONE);
			tvTemperature.setVisibility(View.GONE);
		}
	}

	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				refreshBar.setVisibility(View.VISIBLE);
				break;
			case 1:
				updateWeather();
				refreshBar.setVisibility(View.GONE);
				break;
			case 2:
				refreshBar.setVisibility(View.GONE);
				break;
			}
		}
	};

	/**
	 * 解析天气数据
	 * @param relpy
	 * @return
	 */
	public String parserResult(String reply){
		if("".equalsIgnoreCase(reply)){
			return null;
		}
		
		// 解析天气预报报文, 获得数据.
		int _lowIndex1 = reply.indexOf("<low>");
		int _lowIndex2 = reply.indexOf("</low>");
		int _highIndex1 = reply.indexOf("<high>");
		int _highIndex2 = reply.indexOf("</high>");
		
		//判断是白天还是夜晚
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		String date = sdf.format(new Date());
		String hour = "00";
		if(date.length() == 10)
			hour = date.substring(8, 10);
		
		int _codeIndex1 = -1;
		int _codeIndex2 = -1;
		int _nameIndex1 = -1;
		int _nameIndex2 = -1;
		int _windIndex1 = -1;
		int _windIndex2 = -1;
		
		if(hour.compareTo("06") > -1 && hour.compareTo("18") < 1){
			// 取白天天气.
			int _dayIndex1 = reply.indexOf("<day>");
			int _dayIndex2 = reply.indexOf("</day>");
			if(_dayIndex1 > -1 && _dayIndex2 > -1){
				_codeIndex1 = reply.indexOf("<code>", _dayIndex1);
				_codeIndex2 = reply.indexOf("</code>", _dayIndex1);
				_nameIndex1 = reply.indexOf("<name>", _dayIndex1);
				_nameIndex2 = reply.indexOf("</name>", _dayIndex1);
				_windIndex1 = reply.indexOf("<daywind>", _dayIndex1);
				_windIndex2 = reply.indexOf("</daywind>", _dayIndex1);
				
				if(_codeIndex1 < _dayIndex2 && _codeIndex2 < _dayIndex2){
					// 取天气图片
					code = reply.substring(_codeIndex1 + 6, _codeIndex2);
				}else
					code = "1";
				if(_nameIndex1 < _dayIndex2 && _nameIndex2 < _dayIndex2){
					// 取天气描述
					name = reply.substring(_nameIndex1 + 6, _nameIndex2);
				}else
					name = "N/A";
				if(_windIndex1 > -1 && _windIndex2 > -1){
					// 取风向描述.
					wind = reply.substring(_windIndex1 + 9, _windIndex2);
				}else
					wind = "N/A";
			}else{
				code = "N/A";
				name = "N/A";
				wind = "N/A";
			}
		}else{
			// 取夜间天气.
			int _nightIndex1 = reply.indexOf("<night>");
			int _nightIndex2 = reply.indexOf("</night>");
			if(_nightIndex1 > -1 && _nightIndex2 > -1){
				_codeIndex1 = reply.indexOf("<code>", _nightIndex1);
				_codeIndex2 = reply.indexOf("</code>", _nightIndex1);
				_nameIndex1 = reply.indexOf("<name>", _nightIndex1);
				_nameIndex2 = reply.indexOf("</name>", _nightIndex1);
				_windIndex1 = reply.indexOf("<daywind>", _nightIndex1);
				_windIndex2 = reply.indexOf("</daywind>", _nightIndex1);
				
				if(_codeIndex1 < _nightIndex2 && _codeIndex2 < _nightIndex2){
					// 取天气图片
					code = reply.substring(_codeIndex1 + 6, _codeIndex2);
				}else
					code = "1";
				if(_nameIndex1 < _nightIndex2 && _nameIndex2 < _nightIndex2){
					// 取天气描述
					name = reply.substring(_nameIndex1 + 6, _nameIndex2);
				}else
					name = "N/A";
				if(_windIndex1 > -1 && _windIndex2 > -1){
					// 取风向描述.
					wind = reply.substring(_windIndex1 + 9, _windIndex2);
				}else
					wind = "N/A";
			}else{
				code = "N/A";
				name = "N/A";
				wind = "N/A";
			}
		}
		
		if(_lowIndex1 > -1 && _lowIndex2 > -1)   // 温度下限
			low = reply.substring(_lowIndex1 + 5, _lowIndex2);
		else
			low = "N/A";
		if(_highIndex1 > -1 && _highIndex2 > -1) // 温度上限
			high = reply.substring(_highIndex1 + 6, _highIndex2);
		else 
			high = "N/A";
		
		return "success";
	}
	
	public class AsyncRefreshTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			handler.sendEmptyMessage(0);
			String result = null;
			try{
				String url = ConfigManager.SERVER_URI+"/weather/get_weather?city="
							+Utils.escapeURIComponent(params[0])
							+"&date="+Utils.getNowDate();
				Object reply = LPMid.getInstance().hm_.sendPostRequest(url, null, null, null, null);
				if(null != reply && reply instanceof String){
					Utils.printOutToConsole((String)reply);
					result = parserResult((String)reply);					
				}else{
					result = "success";
				}
			}catch(Exception e){
				result = null;
				bv.handleException(e.getMessage());
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if(null != result && !"".equalsIgnoreCase(result)){
				handler.sendEmptyMessage(1);
			}else{
				handler.sendEmptyMessage(2);
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onClick(View arg0) {
		if (null != BCMHomeView.mSelectCity) {
			// 调用首页城市控件
			BCMHomeView.mSelectCity.showWindow();
		}
	}
	
}
